package com.niit.blog.interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.niit.blog.util.JwtUtils;
import com.niit.blog.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器执行了");
        //获取请求URL
        String url = request.getRequestURL().toString();

        //判断请求URL中是否包含login，如果包含，说明是登录操作则放行
        if (url.contains("login")){
            log.info("登录操作，放行....");
            return true;
        }
        //获取请求头中的令牌
        String jwt = request.getHeader("token");
        //判断令牌是否存在，若不存在则返回错误信息
        if (!StringUtils.hasLength(jwt)){
            log.info("请求头中没有token，返回错误信息....");
            Result error = Result.error("NOT_LOGIN");
            /*手动转换对象为JSON数据*/
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }
        //解析token，若失败返回错误信息
        try {
            JwtUtils.parseJWT(jwt);
        }catch (Exception e){
            log.info("token解析失败，返回错误信息....");
            Result error = Result.error("NOT_LOGIN");
            /*手动转换对象为JSON数据*/
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }
        //放行
        log.info("token解析成功，放行....");
        return true;//true是放行数据 false是不放行
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle、、、");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("拦截器执行完毕");
    }
}
